<template>
  <div>
    <!--左 上下-->
    <el-row type="flex">
      <el-col :md="18" :xs="24">
        <div class="article-left">
          <el-card>
            <div class="article-title">
              <h1>{{data.title}}</h1>
              <div class="article-count">
                <nuxt-link :to="`/user/${data.userId}`" target="_blank">
                  <i class="el-icon-user-solid">{{data.nickName}}&nbsp; &nbsp;</i>
                </nuxt-link>

                <span>
                <!--<i class="el-icon-date">{{getDateFormate(data.updateDate)}}&nbsp; &nbsp;</i>-->
                <i class="el-icon-thumb">{{data.thumhup}}&nbsp; &nbsp;</i>
                <i class="el-icon-view">{{data.viewCount}}&nbsp; &nbsp;</i>
                </span>

                <nuxt-link v-if="$store.state.userInfo && $store.state.userInfo.uid === data.userId "
                           :to="{path: '/question/edit', query: {id: data.id} }" class="nickname">
                  编辑
                </nuxt-link>
              </div>

              <el-tag style="margin: 5px" v-for="item in data.labelList" :key="item.id" size="small">{{item.name}}
              </el-tag>

            </div>
            <div class="article-content">
              <div class="markdown-body" v-html="data.htmlContent"></div>
            </div>
            <!-- plain为true，背景不是深蓝色，为false是深蓝色 -->
            <el-button @click="handleThumb" icon="el-icon-thumb"
                       type="primary" size="medium" :plain="!isThumb">
              赞
            </el-button>
          </el-card>
          <div>
            <h2>精彩回答</h2>
            <el-card v-if="!commentList || commentList.length === 0">
              <h4>暂无回答</h4>
            </el-card>
            <!--每个回答是一个card-->
            <el-card v-else v-for="comment in commentList" :key="comment.id">
              <comment userId="userId" :userImage="userImage"
                       :authorId="data.userId" :showComment="false"
                       :commentList="[comment]" @doChildSend="doChildSend" @doRemove="doRemove"
              >
              </comment>
            </el-card>
          </div>
          <div>
            <h2>编写回答</h2>
            <el-card v-if="!$store.state.userInfo">
              <h4>登录后参与交流、获取后续更新提醒</h4>
              <div>
                <el-button @click="$store.dispatch('loginPage')" type="primary" size="small">登录</el-button>
                <el-button  @click="$store.dispatch('loginPage')" type="primary" size="small" plain>注册</el-button>
              </div>
            </el-card>
            <!-- markdown编辑器，提交回答内容 -->
            <div v-else>
              <!--
                  ref 就是唯一标识，相关于id
                  v-model 绑定的markdown输入 框的内容
              -->
              <mavon-editor :autofocus="false" ref="md" v-model="mdContent" @change="getMdHtml"
                            @imgAdd="uploadContentImg" @imgDel="delConentImg"
              />
              <el-row style="margin-top: 20px" type="flex" justify="center">
                <el-button type="primary" @click="submitReplay">
                  提交问答
                </el-button>
              </el-row>
            </div>
          </div>
        </div>
      </el-col>
      <el-col class="hidden-sm-and-down" :md="6">
        <el-row>
          <el-col>
            <affix :offset="80">
              <directory parentClass="article-content">
              </directory>
            </affix>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {dateFormat} from '@/utils/date.js'
  //固钉
  import affix from '@/components/Affix/index.vue'
  //目录
  import directory from '@/components/Directory/index.vue'
  //评论组件
  import comment from '@/components/Comment'

  export default {
    components: {
      affix,
      directory,
      comment
    },
    // 校验路由参数是否有效
    validate({params}) {
      const id = params.id ? params.id : 0
      // 必须是数值
      return /^\d+$/.test(id)
    },

    data() {

      return {
        //是否点赞
        isThumb: this.$cookies.get(`article-thumb-${this.$route.params.id}`) || false,
        userId: this.$store.state.userInfo && this.$store.state.userInfo.uid,
        //    当前登录用户头像url
        userImage: this.$store.state.userInfo && this.$store.state.userInfo.imageUrl,
        mdContent: '', // 回答内容 md格式
        htmlContent: '' // 回答内容 html格式
      }
    },
    methods: {
      getDateFormate(date) {
        return dateFormat(date)
      },
      // 点赞
      async handleThumb() {
        // 取消点赞或者点赞
        this.isThumb = !this.isThumb
        console.log("this.isThumb" + this.isThumb)
        // 1. 点赞，-1取消赞
        const count = this.isThumb ? 1 : -1
        console.log("count" + this.isThumb)
        const questionId = this.$route.params.id
        const {code} = await this.$updateQuestionThumb(questionId, count)
        if (code === 200) {
          // 更新下当前问题页面显示的点赞数
          this.data.thumhup = this.data.thumhup + count
          // 保存cookie，永久保存
          this.$cookies.set(`question-thumb-${this.$route.params.id}`, this.isThumb, {
            maxAge: 60 * 60 * 24 * 365 * 5 // 保存5年
          })
        }
      },
      //发布回复评论
      async doChildSend(htmlContent, parentId = -1,mdContent='') {
        console.log("发布回复评论" + htmlContent + parentId)
        console.log("mdContent" + mdContent )
        const data = {
          htmlContent,//这里是简写
          mdContent,//这里是简写   md格式内容
          parentId: parentId,
          questionId: this.$route.params.id,
          userId: this.userId,
          userImage: this.userImage,
          nickName: 'aa'
        }
        this.$insertQuestionReplay(data).then(response => {
          if (response.code == 200) {
            //刷新评论信息
            this.refreshComment()
          }
        })
      },
      //删除评论
      async doRemove(id) {
        console.log("删除评论" + id)
        const {code} = await this.$deleteQuestionReplayById(id);
        if (code == 200) {
          this.refreshComment();
        }
      },
      //刷新问答信息
      async refreshComment() {
        const {data: commentList} = await this.$getQuestionReplayById(this.$route.params.id)
        this.commentList = commentList;
      },
      // 获取问答输入框的内容
      getMdHtml(mdContent, htmlContent) {
        this.mdContent = mdContent
        this.htmlContent = htmlContent
      },

      // 上传回答内容图片（图片位置编号，File对象）
      uploadContentImg(pos, file) {
        // 封装表单数据
        const fd = new FormData()
        fd.append('file', file.file)

        this.$uploadImg(fd).then(response => {
          if(response.code === 200) {
            // 上传成功，回显，
            this.$refs.md.$img2Url(pos, response.data)
          }
        })
      },

      // 删除回答内容图片
      delConentImg(urlAndFileArr) {
        const fileUrl = urlAndFileArr[0] //图片url
        const file = urlAndFileArr[1] //File对象
        // 删除内容图片
        this.$deleteImg(fileUrl)
      },

      // 提交回答
      submitReplay() {
        if(this.htmlContent) {
          // 发送回答信息
          this.doChildSend(this.htmlContent, -1, this.mdContent)
        }else {
          this.$message.error('请输入回答内容')
        }
      }

    },
    async asyncData({params, app}) {
      const questionId = params.id ? params.id : null
      console.log("questionId" + questionId)
      const {data} = await app.$getQuestionById(questionId)
      console.log("问题详情data" + data)
      // app.$getQuestionById(questionId).then(response=>{
      //   console.log("response="+response.code)
      //   console.log("data="+response.data)
      // }).catch(error=>{
      //
      // })
      //更新浏览数 将本次查询文章的id 保存到cookie 若cookie不存在则更新
      //当浏览器关闭后会自动将此文章的cookie清除

      const isView = app.$cookies.get(`question-view-${questionId}`);
      if (!isView) {
        //没有值 则更新浏览数
        const {code} = await app.$updateQuestionViewCount(questionId)
        if (code == 200) {
          //将此文章浏览数+1
          data.viewCount++
          //保存到cookies
          app.$cookies.set(`question-view-${questionId}`, true)
        }
      }
      console.log("问题详情的用户id" + data.userId)
      //通过问题id 查询所有回答列表信息
      const {data: commentList} = await app.$getQuestionReplayById(params.id)
      console.log("code=" + data.code + "commentList=" + data.commentList)
      return {data, commentList}
    },
  }
</script>

<style scoped>
  /*  //高亮显示样式*/
  @import "assets/css/md/github-markdown.css";
  @import "assets/css/md/github-min.css";
  @import "assets/css/blog/article.css";
</style>
